<template>
    <div>
        <el-dialog custom-class="definedModal" title="支付" width="550px" :visible="payModal" append-to-body
                   @close="payModal=false">
            <div class="pay">
                <div class="title" style="margin-left: 20px">
                    <div>
                        订单：<span>{{orderInfo.title}}</span>
                    </div>
                    <div>
                        需支付金额：<span>￥&nbsp;{{orderInfo.finalPrice}}</span>
                    </div>
                </div>
                <div class="payWay">
                    <div v-for="(way,index) in payWays" :class="payType===way.type? 'color'+way.type+' active':''"
                         @click="payWayChange(index)">
                        <svg class="icon" aria-hidden="true">
                            <use style="font-size: 20px" :xlink:href="way.icon"></use>
                        </svg>
                        <span>{{way.text}}</span>
                    </div>
                </div>
                <div class="buttons">
                    <!--<el-button type="info" @click="payModal=false">取消</el-button>-->
                    <el-button type="primary" @click="toPay">立即支付</el-button>
                </div>
            </div>
            <el-dialog :custom-class="'bank definedModal'" title="银行转账" width="650px" :visible="bankModel"
                       @close="closeBankModal"
                       append-to-body>
                <el-form ref="bankForm" :model="bankInfo" :rules="bankInfo.rules">
                    <div class="bank-info can-select">1.&nbsp;汇款验证码：<a>{{bankInfo.tradeNum}}</a>，请将汇款识别码填写在电汇凭证的“汇款用途”栏目中
                    </div>
                    <div class="bank-info can-select">2.&nbsp;请将活动实付金额转账至开心大屏幕官方银行卡</div>
                    <div class="bank-info can-select">户名：上海XX科技有限公司&nbsp;&nbsp;&nbsp;银行卡号：<span
                            style="padding: 0 10px;text-decoration: underline">31050170380000001250</span></div>
                    <div class="bank-info can-select">开户地址：中国建设银行股份有限公司上海浙江路支行</div>
                    <el-form-item label-width="130px" label="订单号："><a class="can-select">{{bankInfo.tradeNum}}</a>
                    </el-form-item>
                    <el-form-item label-width="130px" label="转款用户名：" prop="userName">
                        <el-input type="text" v-model="bankInfo.userName"></el-input>
                    </el-form-item>
                    <el-form-item label-width="130px" label="联系人手机号：" prop="tel">
                        <el-input type="text" v-model="bankInfo.tel"></el-input>
                    </el-form-item>
                    <el-form-item label-width="130px" label="转款账号：" prop="cardNum">
                        <el-input type="text" v-model="bankInfo.cardNum"></el-input>
                    </el-form-item>
                    <div style="text-align: center;padding-top: 20px">
                        <el-button style="width: 150px" type="primary" @click="bankSubmit">提交</el-button>
                    </div>
                </el-form>
            </el-dialog>
        </el-dialog>
        <el-dialog :visible="codeImgVisible" width="350px" center title="微信扫码支付"
                   @close="codeImgVisible=false" append-to-body :z-index="100">
            <div style="text-align: center;font-size: 12px;color: #cccccc;padding-bottom: 20px">打开手机微信app扫码支付</div>
            <div>
                <div v-if="codeImgVisible" id="qrCode"
                     style="text-align: center;display: flex;justify-content: center"></div>
                <div style="text-align: center;margin-top: 20px">
                    <el-button @click="codeImgVisible=false">关闭</el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import QRCode from 'qrcodejs2';
    import moment from 'moment';

    let dateFormatDT = (val) => {
        return moment(val).format('YYYY-MM-DD HH:mm:ss');
    };
    let dateFormatDD = (val) => {
        return moment(val).format('YYYY-MM-DD');
    };
    let payCode = {
        wx: {
            padding: { payStatus: 3, describe: '支付中', payType: 0 },
            success: { payStatus: 1, describe: '支付成功', payType: 0 },
            fal: { payStatus: 0, describe: '支付失败', payType: 0 },
        },
        zfb: {
            padding: { payStatus: 3, describe: '支付中', payType: 1 },
            success: { payStatus: 1, describe: '支付成功', payType: 1 },
            fal: { payStatus: 0, describe: '支付失败', payType: 1 },
        },
        bank: {
            padding: { payStatus: 3, describe: '支付中', payType: 2 },
            success: { payStatus: 1, describe: '支付成功', payType: 2 },
            fal: { payStatus: 0, describe: '支付失败', payType: 2 },
        },
    };
    export default {
        name: 'pay',
        data() {
            return {
                payModal: false,
                searchLoading: false,
                payType: 0,
                bankModel: false,
                orderInfo: {},
                orderNum: '',
                bankInfo: {
                    cardNum: '',
                    tradeNum: '',
                    userName: '',
                    tel: '',
                    rules: {
                        cardNum: [
                            { required: true, message: '请输入您的汇款账号', trigger: 'blur' },
                        ],
                        userName: [
                            { required: true, message: '请输入用户名', trigger: 'blur' },
                        ],
                        tel: [
                            { required: true, message: '请输入手机号码', trigger: 'blur' },
                            { pattern: /^[1][345678][0-9]{9}$/, message: '手机号格式不正确', trigger: 'change' },
                        ],
                    },
                },
                payWays: [
                    { icon: '#ss-weixinzhifu', text: '微信', type: 0 },
                    { icon: '#ss-zhifubao', text: '支付宝', type: 1 },
                    { icon: '#ss-yinlian', text: '银行转账', type: 2 },
                ],
                codeImgVisible: false,
            };
        },
        mounted() {
            this.$bus.$on('orderPay', (orderNum) => {
                // console.log('orderNum', orderNum);
                this.bankInfo.tradeNum = orderNum;
                if (orderNum) {
                    this.payModal = true;
                    this.$api.get('/order/info', { orderNo: orderNum }, success => {
                        this.orderInfo = success;
                    }, fal => {
                        this.$message.error('获取订单信息失败');
                    });

                }
            });
            let query = this.$route.query;
            if (query && query.out_trade_no) {
                this.$router.push({path:this.$route.path});
                this.sendPayStatus(payCode.zfb.success, query.out_trade_no);
            }
        },
        methods: {
            closeBankModal() {
                this.payType = 0;
                this.bankModel = false;
            },
            payWayChange(index) {
                if (index === 2) {
                    this.payType = this.payWays[index].type;
                    this.toPay();
                } else {
                    this.payType = this.payWays[index].type;
                }
            },
            toPay() {
                switch (this.payType) {
                    case 0:
                        this.sendPayStatus(payCode.wx.padding, this.bankInfo.tradeNum);
                        this.$api.get('/pay/wxpay/nativetest', { out_trade_no: this.bankInfo.tradeNum }, success => {
                            this.payModal = false;
                            this.showQRcode(success);
                        }, fal => {
                            this.sendPayStatus(false);
                            this.$message.error('支付失败');
                        });
                        break;
                    case 1:
                        this.sendPayStatus(payCode.zfb.padding, this.bankInfo.tradeNum);
                        this.$api.get('/pay/alipay/webtest', { out_trade_no: this.bankInfo.tradeNum }, success => {
                            this.payModal = false;
                            let div = document.createElement('div');
                            div.innerHTML = success;
                            document.body.appendChild(div);
                            div.getElementsByTagName('form')[0].submit();
                        }, fal => {
                            this.sendPayStatus(false);
                            this.$message.error('支付失败');
                        });
                        break;
                    case 2:
                        this.bankModel = true;
                        break;
                }
            },
            bankSubmit() {
                let info = this.bankInfo;
                this.$refs.bankForm.validate((res) => {
                    if (res) {
                        let bankPayDetail = {
                            cardNum: info.cardNum,
                            userName: info.userName,
                            tel: info.tel,
                        };
                        this.$api.post('/order/bankPay', { bankPayDetail, orderNo: info.tradeNum }, success => {
                            this.payModal = false;
                            this.$alert('<div style="margin: 20px">请联系管理人员开通场景，电话：<span style="user-select: text;">2034-65789</span></div>', '提示', {
                                confirmButtonText: '确定',
                                dangerouslyUseHTMLString: true,
                            });
                        }, fal => {
                            this.$message.error(fal);
                        });
                    }
                });
            },
            showQRcode(text) {
                this.codeImgVisible = true;
                setTimeout(() => {
                    let qrcode = new QRCode(document.getElementById('qrCode'), {
                        width: 200,
                        height: 200, // 高度
                        text,  // 二维码内容
                        render: 'canvas',  // 设置渲染方式（有两种方式 table和canvas，默认是canvas）
                    }, 100);
                });
            },
            sendPayStatus(obj, orderNum) {
                if (obj) {
                    this.$bus.$emit('payStatus', obj);
                    if (window.sendPayStatus) {
                        clearInterval(window.sendPayStatus);
                    }
                    this.orderNum = orderNum;
                    window.sendPayStatus = setInterval(() => {
                        this.$api.get('/order/info', { orderNo: this.orderNum }, success => {
                            let TYPE = '';
                            switch (this.payType) {
                                case 0:
                                    TYPE = 'wx';
                                    break;
                                case 1:
                                    TYPE = 'zfb';
                                    break;
                                case 2:
                                    TYPE = 'bank';
                                    break;
                                default:
                                    TYPE = 'wx';
                                    break;
                            }
                            if (success.payStatus && success.payStatus === 1) {
                                //支付成功提示信息
                                this.message(success);
                                //隐藏微信二维码
                                this.codeImgVisible = false;
                                //分发支付成功的状态
                                this.$bus.$emit('payStatus', payCode[TYPE].success);
                                //清除定时获取订单信息
                                window.clearInterval(window.sendPayStatus);
                            } else {
                                this.$bus.$emit('payStatus', payCode[TYPE].padding);
                            }
                        }, fal => {
                            this.$bus.$emit('payStatus', payCode.wx.fal);
                            console.log('获取订单状态失败:', fal, this.orderNum);
                            clearInterval(window.sendPayStatus);
                        }, null, true);
                    }, 3000);
                    setTimeout(() => {
                        clearInterval(window.sendPayStatus);
                        this.$bus.$emit('payStatus', payCode.wx.fal);
                    }, 5 * 60 * 1000);
                } else {
                    clearInterval(window.sendPayStatus);
                    this.$bus.$emit('payStatus', payCode.wx.fal);
                }
            },
            message(info) {
                //  type:  1 场景发布 2 开通会员 3 会员升级 4 场景升级 5 会员续费
                //  payType : 0  微信  1  支付宝  2 银行卡
                if (info.type == 2 || info.type == 3 || info.type == 5) {
                    this.$bus.$emit('refreshMemberInfo');
                }
                if (info.type == 1) {
                    this.$bus.$emit('refreshScenes');
                }
                let html = ``, title = '';
                let detail = info.detail ? JSON.parse(info.detail) : {};
                switch (parseInt(info.type)) {
                    case 1:
                        title = `活动发布成功`;
                        html = `<div><div class="title">${title}</div><div class="date">活动有效期：${dateFormatDT(detail.startTime)}<span style="padding: 0 10px">至</span>${ dateFormatDT(detail.endTime)}</div></div>`;
                        break;
                    case 2:
                        title = this.orderInfo.title.replace(/[开通升级续费]/g, '');
                        html = `<div><div class="tip">恭喜您成为</div><div class="title">${title}</div><div class="date">会员有效期：${ dateFormatDD(detail.current.startDate)}<span style="padding: 0 10px">至</span>${  dateFormatDD(detail.current.endDate)}</div></div>`;
                        break;
                    case  3:
                        title = this.orderInfo.title.replace(/[开通升级续费]/g, '');
                        html = `<div><div class="tip">恭喜您成为</div><div class="title">${title}</div><div class="date">会员有效期：${ dateFormatDD(detail.current.startDate)}<span style="padding: 0 10px">至</span>${  dateFormatDD(detail.current.endDate)}</div></div>`;
                        break;
                    case  5:
                        title = this.orderInfo.title.replace(/[开通升级续费]/g, '');
                        html = `<div><div class="tip">会员续费成功</div><div class="title">${title}</div><div class="date">会员有效期：${ dateFormatDD(detail.current.startDate)}<span style="padding: 0 10px">至</span>${ dateFormatDD(detail.current.endDate)}</div></div>`;
                        break;
                    case 4:
                        title = ` 活动升级成功`;
                        html = `<div><div class="title">${title}</div></div>`;
                        break;
                }
                this.showMessage(html);
            },
            showMessage(html) {
                let text = '支付成功';
                this.$alert(html, text, {
                    dangerouslyUseHTMLString: true,
                    customClass: 'payMessage',
                });
            },
        },
    }
    ;
</script>

<style scoped lang="scss">
    .icon {
        width: 2em;
        height: 2em;
        vertical-align: -0.15em;
        fill: currentColor;
        overflow: hidden;
    }

    .title {
        div {
            margin: 10px;
            font-weight: 600;
            span {
                padding-left: 20px;
                color: #666666;
            }
        }
    }

    .coupons {
        @include flex;
        .label {
            width: 100px;
            text-align: right;
        }
        .name {
            @include flex;
            width: calc(100% - 100px);
            div {
                width: 150px;
            }
            button {
                margin: 0 20px 0 5px;
                transition: all .3s;
            }
        }

    }

    .payWay {
        @include flex-ad;
        padding: 20px;
        & > div {
            padding: 10px;
            @include flex-ad;
            width: 150px;
            border: 1px solid #cccccc;
            background: #ffffff;
            border-radius: 5px;
            transition: all .3s;
            position: relative;
            color: #dddddd;
            cursor: pointer;
        }
        & > div:after{
            content: ' ';
            position: absolute;
            width: 100%;height: 100%;
            transition: all .4s;
        }
        & > div:hover {
            border-color: #46b09f;
        }
        div.active {
            color: #333;
        }
        .color0.active{
            border-color: #41B035;
        }
        .color1.active{
            border-color: #4199eb;
        }
        .color2.active{
            border-color: #d23431;
        }
        div.active:after{
            background: rgba(0, 0, 0,0);
        }
    }

    .buttons {
        text-align: center;
        padding: 20px;
        button {
            width: 150px;
            background: #FA1919;
            border: none;
            border-radius: 20px;
        }
        button:hover{
            background: #ff3535;
            box-shadow: 3px 4px 4px 0 rgba(0, 0, 0, 0.20);
        }
    }

    .bank {
        @include container-border;
        border-radius: 10px;

        .bank-info {
            padding: 10px 20px;
            font-size: 16px;
        }

    }

    .can-select {
        user-select: text;
    }
</style>